package n.info.activities;

import n.info.R;
import n.info.adapters.FeedItemAdapter;
import n.info.entities.Feed;
import n.info.entities.FeedItem;
import n.info.entities.FeedSite;
import n.info.xml.SaxFeedParser;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class FeedReaderActivity extends Activity {

	// ~ constants .................................................................................
	
	public static final String ACTION_FEED_READER = "n.info.feed_reader" ;
	public static final String EXTRA_FEED_SITE_POSITION = "feed_site_position" ;
	
	// ~ Static fields/initializers .............................................................
	// ~ Static methods ........................................................................
	// ~ Instance fields .........................................................................

	ProgressBar progressBar ;
	
	FeedSite feedSite ;
	Feed feed ;
	
	// ~ overriden methods .................................................................................
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feed_reader);
        
        // Progress Bar
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        
        Intent intent  = getIntent();
        if(ACTION_FEED_READER.equals(intent.getAction())){
        	int position = intent.getIntExtra(EXTRA_FEED_SITE_POSITION, -1);
        	feedSite = FeedSite.getList().get(position);
        	
        	// Check orientation change
            Object object =  getLastNonConfigurationInstance() ;
            if(object != null){
         	   feed = (Feed) object ;
         	   refreshListView() ;
            }
            else{
            	requestFeed(feedSite.getRss()) ;
            }
        }

    }

    
    /** Called when orientation changed */
    @Override
    public Object onRetainNonConfigurationInstance() {
    	return feed ;
    }
    
	// ~ Methods ..................................................................................	
    
    private void refreshListView(){
    	progressBar.setVisibility(View.GONE);
    	if(feed != null){
    		
    		ListView listView = (ListView)findViewById(R.id.listViewFeedReader);
    		FeedItem[] feedItems = feed.getItems().toArray(new FeedItem[]{}) ;
	        FeedItemAdapter adapter = new FeedItemAdapter(this, feedItems);
	        listView.setAdapter(adapter);
	        adapter.notifyDataSetChanged();
    	}
    }
    
    private void toast(String msg){
    	Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
    
    private void requestFeed(String url){
      	
    	new AsyncTask<String, Void, Feed>() {
    		
    		Exception e ;
    		
			@Override
            protected Feed doInBackground(String... params) {
				Feed feed = null;
				try {
	                feed = new SaxFeedParser(params[0]).parse();
                }
                catch (Exception e) {
                	try {
    	                feed = new SaxFeedParser(params[0]).parseAtom();
                    }
                    catch (Exception ex) {
                    	this.e = ex ;
    	                ex.printStackTrace();
                    }
                }
				return feed ;
            }
			
			@Override
			protected void onPostExecute(Feed f) {
				if(e != null)
					toast("error retrieving feed");
				
				feed = f ;
				refreshListView() ;
			}
    		
    	}.execute(url);
    	        
    }
    
	// ~ Inner classes ...........................................................................
}
